<template>
  <view class="back_washing">
    <public-loading></public-loading>
    <up-toast ref="uToastRef"></up-toast>
    <z-nav-bar id="nav" bgColor="#ffffff" title="我要返洗"></z-nav-bar>
    <view class="order_info_wrap mgt-24">
      <view class="order_info_box df justify-between item-bottom-border">
        <view class="order_info_left">订单编号</view>
        <view class="order_no">{{orderDetailsInfo.orderId }}</view>
      </view>
      <view class="order_info_box df justify-between">
        <view class="order_info_left">下单时间</view>
        <view class="order_no">{{orderDetailsInfo.createTime }}</view>
      </view>
    </view>
    <view class="order_choose_wrap mgt-24">
      <view class="order_info_title">选择返洗的衣服</view>
      <view class="goods_list mgt-24">
        <view
          class="goods-item df mgb-15"
          v-for="(item, index) in state.list"
          :key="index"
        >
          <image
            class="goods-image"
            :src="item.clothingTypeImages"
            mode="aspectFill"
          ></image>
          <view class="goods-detail_wrap flex1 mgl-24 mgt-24">
            <view class="goods-detail df flex-jc-sb">
              <view class="goods-name df">
                <text>{{ item.clothingType }}</text>
                <view class="flex1 mgl-15">
                <text class="price-value">x{{ item.count }}</text>

                </view>
              </view>
              <view @tap="item.flag=!item.flag">
                <single-select :selectShow="item.flag" :scale="'scale(0.66)'" :borderColor="'#999'"></single-select>
              </view>
            </view>
            <view class="goods-price df flex-jc-sb mgt-12">
              <view class="price-symbol df">
                <text>{{item.type}}</text>
                <view class="flex1" v-if="item.garmentRemark">
                  <up-tag class="mgr-15" v-for="(self,i) in item.garmentRemark.split(',')" :key="i" :text="self" plain size="mini" > </up-tag>
                </view>
              </view>
              <up-tag text="添加原因"  size="mini" @click="openPopup(item)"> </up-tag>
            </view>
          </view>


        </view>
        <!--        订单的详情-->
      </view>
    </view>
    <view class="bottom-btn-box df flex-jc-end" >
      <main-button  :width="'168rpx'"   :color="'#fff'" :margin="'24rpx 0 0'" @click="submitBackwashing">提交返洗</main-button>
      <main-button class="mgl-24" :isGradient="false" :width="'168rpx'"  :color="'#333'" :margin="'24rpx 0 0'" @click="submit">联系店铺</main-button>
    </view>
    <!-- 优惠券蒙版层 -->
    <up-popup :show="show" mode="bottom" :round="10" @close="close" @open="open" :closeable="true">
      <view class="content_popup">
        <view class="content_title">添加原因</view>
        <view class="content_input_wrap mgt-30">
          <up-textarea v-model="washbackReason" placeholder="请添加返洗原因" border="none"  style="background-color:#f3f3f5;"></up-textarea>
               <z-upload-image limit="6" v-model:files="specialPic" action-type="custom">
                  <view class="img-upload">
                    <view class="img-item flex-aj-center">
                      <view class="side">
                        <view class="side"></view>
                      </view>
                    </view>
                  </view>
              </z-upload-image>
        </view>
           <main-button :color="'#fff'" :margin="'40rpx 0 0'" @click="confirmReason">确认</main-button>

      </view>
    </up-popup>
  </view>
</template>

<script setup>
import {ref,reactive} from 'vue'
import {useCustomStores} from '@/utils/hook'
import {customerAddAfterSales} from '../../api/cleaningOrder'
const {ShopStore} = useCustomStores()
const uToastRef = ref(null)
const {orderDetailsInfo} = ShopStore
const show = ref(false);
const currentItemId = ref(null);
const currentOrderItemId = ref(null);
const washbackReason = ref('');
const specialPic = ref('');

// 存储每件衣物的原因和图片
const itemReasons = reactive({});

// 存储所有衣物的返洗信息
const afterSalesItems = ref([]);

const state = reactive({
  list: orderDetailsInfo.hemaOrderItemBriefVos.map(item => {
    return {
      ...item,
      flag: false
    }
  })
});
function submitBackwashing(){
  const selectedItems = state.list.filter(item => item.flag);

  if(selectedItems.length <= 0){
    uToastRef.value.show({
      type: 'default',
      message: '请选择返洗衣物',
    })
    return
  }

  // 检查选中的衣物是否都填写了原因和上传了图片
  const invalidItem = selectedItems.find(item => {
    const afterSaleItem = afterSalesItems.value.find(afterItem => afterItem.itemId === item.id);
    return !afterSaleItem || !afterSaleItem.washbackReason || !afterSaleItem.garmentImages;
  });

  if(invalidItem) {
    uToastRef.value.show({
      type: 'default',
      message: '请为所有选中衣物添加返洗原因和上传图片',
    })
    return
  }

  customerAddAfterSales({
    ids: selectedItems.map(item => item.id),
    afterSalesItems: afterSalesItems.value,
    orderNo: orderDetailsInfo.orderId,
    storeId: orderDetailsInfo.storeId,
    afterSalesProcess: 'WASHBACK',
    orderStatus: '40'
  }).then(res=>{
    uToastRef.value.show({
      type: 'success',
      message: '返洗申请提交成功',
    })
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }).catch(err=>{
    uToastRef.value.show({
      type: 'error',
      message: err.message || '提交失败，请稍后重试',
    })
  })
}

// 打开弹窗前检查
const openPopup = (item) => {
  if (!item.flag) {
    uToastRef.value.show({
      type: 'default',
      message: '请先选择该衣物',
    })
    return
  }
  currentItemId.value = item.id;
  currentOrderItemId.value = item.orderItemId;
  // 如果之前有填写过，恢复之前的数据
  const existingItem = afterSalesItems.value.find(afterItem => afterItem.itemId === item.id);
  if (existingItem) {
    washbackReason.value = existingItem.washbackReason;
    specialPic.value = existingItem.garmentImages;
  } else {
    washbackReason.value = '';
    specialPic.value = '';
  }
  show.value = true;
}

// 确认添加原因
const confirmReason = () => {
  if (!washbackReason.value) {
    uToastRef.value.show({
      type: 'default',
      message: '请填写返洗原因',
    })
    return
  }

  if (!specialPic.value || specialPic.value.length === 0) {
    uToastRef.value.show({
      type: 'default',
      message: '请上传图片',
    })
    return
  }

  // 更新或添加返洗信息到数组
  const existingIndex = afterSalesItems.value.findIndex(item => item.itemId === currentItemId.value);
  const newItem = {
    itemId: currentItemId.value,
    washbackReason: washbackReason.value,
    garmentImages: specialPic.value,
    orderItemId:currentOrderItemId.value

  };

  if (existingIndex > -1) {
    // 更新现有数据
    afterSalesItems.value[existingIndex] = newItem;
  } else {
    // 添加新数据
    afterSalesItems.value.push(newItem);
  }

  show.value = false;
}

// 关闭弹窗
const close = () => {
  show.value = false;
}
</script>

<style lang="scss" scoped>
.back_washing{
  box-sizing: border-box;
  width: 100%;
  padding: 0 32rpx;
  .order_info_wrap{
    box-sizing: border-box;
    width: 100%;
    padding: 0 32rpx;
    border-radius: 16rpx;
    background-color: #FFFFFF;
    .order_info_box{
      padding: 32rpx;
      .order_info_left{
        font-weight: bold;
        font-size: 28rpx;
        color: #000000;
      }
      .order_no{
        font-weight: 400;
        font-size: 28rpx;
        color: #444444;
      }

    }
  }
  .order_choose_wrap{
    width: 100%;
    .order_info_title{
      font-weight: bold;
      font-size: 28rpx;
      color: #000000;
    }
    .goods_list{
      box-sizing: border-box;
      padding:32rpx 24rpx;
      width: 100%;
      border-radius: 16rpx;
      background-color: #FFFFFF;
      .goods-item{
        .goods-image{
          width: 120rpx;
          height: 120rpx;
          border-radius: 8rpx;
          //background-color: #f5f5f5;
          flex-shrink: 0;
        }
        .goods-detail{
          .goods-name{
            font-size: 32rpx;
            color: #333333;
          }
          .goods-type{
            font-size: 32rpx;
            color: #333333;
          }
        }
        .goods-price{
          .price-symbol{
            font-size: 32rpx;
            color: #999999;
          }
          .price-value{
            font-size: 32rpx;
            color: #999999;
          }
        }
      }
      .goods_bottom{
        margin-bottom: 20rpx;
        .goods_lab_wrap{

        }
        .goods_bottom_right{
          font-size: 32rpx;
          color: #333333;
          .total-price{
            font-size: 32rpx;
            color: #ff3333;
          }
        }
      }

    }
  }
}
.content_popup{
  box-sizing: border-box;
  width: 100%;
  padding: 32rpx;
  min-height: 600rpx;
  .content_title{
    width: 100%;
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
  }
  .content_input_wrap{
    box-sizing: border-box;
    width: 100%;
    min-height: 300rpx;
    background-color: #f3f3f5;
    border-radius: 20rpx;
    padding:  32rpx;

  }

}

  .img-upload{
    position: relative;
    image{
      width: 132rpx;
      height: 132rpx;
      border-radius: 20rpx;
      background-color: #ccc;
      margin-right: 20rpx;
    }
    .img-item{
      width: 132rpx;
      height: 132rpx;
      border-radius: 20rpx;
      border: 2rpx dashed #ccc;
      color: #ccc;
      font-size: 80rpx;
      font-weight: lighter;
      .side{
        width: 37rpx;
        height: 2.5rpx;
        background-color: #ccc;
        .side{
          width: 37rpx;
          height: 2.5rpx;
          background-color: #ccc;
          transform: rotateZ(90deg);
        }
      }
    }
  }

::v-deep .z-upload-image{
  display: flex!important;
  flex-wrap: wrap;
}
::v-deep .z-image-item {
  width: 132rpx!important;
  height: 132rpx!important;
  border-radius: 16rpx;
  margin: 5rpx 8rpx;
}
</style>
